<template>
  <div class="page-container relative">
    <BaseCollapse title="基础信息">
      <DynamicForm :config="dyConfig" :questions="dyQuestions" ref="baseRef" />
    </BaseCollapse>
    <BaseCollapse title="销毁档案列表">
      <DynamicForm :config="destroyListConfig" :questions="destroyListQuestions" ref="fileRef" />
    </BaseCollapse>
    <BaseCollapse v-if="['CONFIRM', 'VIEW'].includes(state.showType)" title="销毁鉴定小组">
      <DynamicForm :config="dyTeamConfig" :questions="dyTeamQuestions" ref="teamRef" />
    </BaseCollapse>
    <BaseCollapse v-if="['CONFIRM', 'VIEW'].includes(state.showType)" title="档案销毁确认">
      <DynamicForm id="confirmBill" :config="dyConfirmConfig" :questions="dyConfirmQuestions" ref="confirmRef">
        <template #reviewer="{ question }">
          <a v-if="['CONFIRM'].includes(state.showType)" class="ml-2.5" href="#" @click.prevent="confirmDestroy">确认销毁</a>
          <CustomImage v-if="question.value" class="w-8 inline-block ml-4" :src="imgUrl(question.value)" />
        </template>
        <template #confirmBill="{ question }">
          <span class="space-x-2">
            <a href="#" @click.prevent="handlePreview">预览</a>
            <a href="#" @click.prevent="handleDown">下载</a>
          </span>
        </template>
      </DynamicForm>
    </BaseCollapse>
    <!-- <BaseCollapse v-if="['AUDIT', 'IDENTIFY'].includes(state.showType)" title="审批意见">
      <DynamicForm :config="dyCommentConfig" :questions="dyCommentQuestions" ref="commentRef" />
    </BaseCollapse> -->
    <ApprovalDetail v-if="['VIEW', 'AUDIT', 'IDENTIFY'].includes(state.showType) && query.processInstanceId" :config="approvalConfig" @back="approvalGoBack"></ApprovalDetail>
    <div class="space-x-2 w-full text-center my-4">
      <a-button v-if="!['AUDIT', 'IDENTIFY'].includes(state.showType)" @click="cancel">返回</a-button>
      <a-button v-if="['ADD', 'EDIT'].includes(state.showType)" @click="submit(0)">暂存</a-button>
      <a-button v-if="['ADD', 'CONFIRM', 'EDIT'].includes(state.showType)" type="primary" @click="submit(1)">提交</a-button>
      <a-button v-if="['VIEW'].includes(state.showType) && [1, 3].includes(state.archiveStatus)" type="primary" @click="handleEdit">编辑</a-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
import AuditRecord from '@/components/common/AuditRecord/index.vue';
import ApprovalDetail from '@/components/approval-details/index.vue';
import BaseCollapse from '@/components/common/BaseCollapse/index.vue';
import CustomImage from '@/components/common/CustomImage/index.vue';
import { DynamicForm } from '@/components/public-template';
import { Api, destroyAuidt, destroyAuthen, destroyAutoProduct, destroyConfirm, destroyFindFile, destroyGet, destroySave } from '@/config/api/archivesFileDestroy';
import { Api as ApiResource, getPreviewFileUrl } from '@/config/api/resourceFileInfo';
import { Api as ApiSystem, findSubjectSeal } from '@/config/api/system';
import { CUSTOMSELECTSERVE, DYNAMICLAYERCLEAR, DYNAMICLAYERFORM, DYNAMICLOCALTABLE, LOCALSUBSERVE, RESETTABLE } from '@/mixins/subject/subject-types';
import { message } from 'ant-design-vue';
import { filter } from 'rxjs/operators';
import { computed, getCurrentInstance, onBeforeUnmount, onMounted, reactive, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import indexService from './index.service';
import { HOST } from '@/config';
import { advancedQueryPreview } from '@/config/api/searchManage';
import { throttle } from 'xe-utils';
import { encryptFn } from '@/utils/crypto';
import html2canvas from 'html2canvas';
import { formInfoStore } from '@/store/modules/form';

const { query } = useRoute();

const state = reactive({
  showType: 'ADD', // enum 'ADD' 'VIEW' 'AUDIT' 'IDENTIFY' 'CONFIRM'
  archiveStatus: null, // 档案状态
  fileList: [] // 档案列表
});
const baseRef = ref(null);
const fileRef = ref(null);
const teamRef = ref(null);
const confirmRef = ref(null);
const commentRef = ref(null);
const route = useRoute();
const router = useRouter();
state.showType = route.query.showType as string;
const approvalConfig: any = ref({
  title: '审批流程',
  showBackBtn: true, //显示返回按钮
  showAgreeBtn: true, //显示同意按钮
  showGoBackBtn: true, // 显示退回按钮
  showRejectBtn: true // 显示拒绝按钮
});

const approvalGoBack = (cb: any) => {
  cb?.();
};
const dyConfig: any = {
  labelCol: 8,
  wrapperCol: 16,
  grid: 6,
  layout: 'vertical',
  cancelSave: true
};
const destroyListConfig: any = {
  queryUrl: state.showType !== 'ADD' ? Api.destroyGetDestroyFiles : null,
  protType: 'post',
  cancelSave: true,
  beforeWithMethod: (data) => {
    if (!Array.isArray(data)) return null;
    return {
      fileList: data
    };
  }
};
const dyTeamConfig: any = {
  labelCol: 10,
  wrapperCol: 24,
  grid: 6,
  layout: 'vertical',
  cancelSave: true
};
const dyConfirmConfig: any = {
  labelCol: 8,
  wrapperCol: 16,
  grid: 6,
  layout: 'vertical',
  cancelSave: true
};
const dySignConfig: any = reactive({
  name: 'signForm',
  title: '确认销毁电子签名',
  width: '390px',
  type: 'layer',
  labelCol: 8,
  wrapperCol: 24,
  grid: 24,
  layout: 'vertical',
  addUrl: ApiSystem.findSubjectSeal,
  localSub: true,
  combinationMethod: (data) => {
    data.password = encryptFn(data.password);
    return data;
  }
});
const dyPreviewConfig: any = {
  name: 'previewForm',
  title: '销毁确认单',
  width: '480px',
  type: 'layer',
  labelCol: 12,
  wrapperCol: 24,
  grid: 12,
  layout: 'vertical',
  cancelSave: true
};
const dyCommentConfig: any = {
  labelCol: 8,
  wrapperCol: 22,
  grid: 6,
  layout: 'vertical',
  cancelSave: true
};
const { proxy }: any = getCurrentInstance();
const dyQuestions: any = reactive(indexService.getQuestions(state.showType));
const destroyListQuestions = reactive(indexService.getDestroyListQuestions(state.showType));
const dyTeamQuestions: any = reactive(indexService.getTeamQuestions(state.showType));
const dyConfirmQuestions: any = reactive(indexService.getConfirmQuestions(state.showType));
const phone = JSON.parse(window.localStorage.getItem('LOGIN__INFO__'))['phone'];
const formStore = formInfoStore();
formStore.setQuestions(indexService.getSignQuestions(phone));
const dySignQuestions = formStore.getQuestions;
// const dySignQuestions: any = reactive(indexService.getSignQuestions());
const dyPreviewQuestions: any = reactive(indexService.getPreviewQuestions());
const dyCommentQuestions: any = reactive(indexService.getCommentQuestions());
const imgUrl = computed(() => {
  return function (imgId) {
    return `${HOST}${ApiResource.resourceViewFile}/${imgId}`;
  };
});
onMounted(() => {
  if (state.showType == 'ADD') {
    destroyAutoProduct(null).then((result) => {
      if (result.success) {
        // 基本信息
        const data = result.data;
        dyQuestions.forEach((item) => (item.value = data[item.key]));
      }
    });
    getFileList();
  } else if (['AUDIT', 'IDENTIFY', 'CONFIRM', 'VIEW', 'EDIT'].includes(state.showType)) {
    state.showType == 'EDIT' && getFileList();
    destroyGet(route.query.id).then((result) => {
      if (result.success) {
        // 基本信息
        const data = result.data;
        state.archiveStatus = result.data.status;
        dyQuestions.forEach((item) => (item.value = data[item.key]));
        // 销毁鉴定小组
        dyTeamQuestions.forEach((item) => (item.value = data[item.key]?.join('；')));
        // 档案销毁确认
        dyConfirmQuestions.forEach((item) => (item.value = data[item.key]));
        console.log(confirmRef.value.getDataFrom(), 'dataform');
      }
    });
  }
  if (['VIEW'].includes(state.showType)) {
    approvalConfig.value.showBackBtn = false;
    approvalConfig.value.showAgreeBtn = false;
    approvalConfig.value.showGoBackBtn = false;
    approvalConfig.value.showRejectBtn = false;
  }
});
const subscribeSub = proxy.$NotificationFormSub
  .getParams()
  .pipe(filter((res) => res !== 0))
  .subscribe((item) => {
    console.log('item', item);
    if (item.key == CUSTOMSELECTSERVE) {
      for (let file of state.fileList) {
        if (item.value.data.key === file.id) {
          destroyListQuestions[0].value[item.value.index] = file;
        }
      }
    } else if (item.key == LOCALSUBSERVE && item.state.name == 'signForm') {
      const params = {
        account: item.value.account,
        password: item.value.password
      };
      findSubjectSeal(params).then((res) => {
        if (res.success) {
          const dataList = res.data;
          // todo 无印章信息提示
          if (!dataList || dataList.length == 0) {
            message.warning('该账号无印章信息, 请前往添加个人印章');
            return;
          } else {
            message.success('提交成功！');
            proxy.$NotificationPubSub.pushParams({ key: DYNAMICLAYERCLEAR, value: { name: 'signForm' } });
          }
          dyConfirmQuestions.forEach((obj) => {
            if (obj.key == 'reviewer') {
              obj.value = dataList[0]; // 默认第一个电子印章
              confirmRef.value.ruleForm[obj.key] = obj.value;
              confirmRef.value.isValidateFields([obj.key]);
            }
          });
        }
      });
    }
  });
const subscribePub = proxy.$NotificationPubSub
  .getParams()
  .pipe(filter((res) => res !== 0))
  .subscribe((item) => {
    console.log('item', item);
    if (item.key == DYNAMICLOCALTABLE && item.value.part.state?.name == 'LOCAL_PREVIEW') {
      advancedQueryPreview({ id: item.value.data.id, needRecord: false }).then((res) => {
        if (res.success && res.data) {
          window.open(res.data, '_blank');
        }
      });
    }
  });
// 获取档案列表
function getFileList() {
  destroyFindFile({}).then((result) => {
    if (result.success) {
      const option = result.data.map((item) => ({ label: item.name, value: item.name, key: item.id }));
      destroyListQuestions.forEach((item) => {
        if (item.key == 'fileList') {
          item.state.columns[1].options = option;
        }
      });
      state.fileList = result.data;
    }
  });
}
function cancel() {
  router.go(-1);
}
function handleEdit() {
  router
    .replace({
      name: 'ArchivesManageAddDestroy',
      query: {
        id: route.query.id,
        showType: 'EDIT'
      }
    })
    .then(() => {
      router.go(0);
    });
}
// 提交 op操作（0=暂存；1=提交）
const submit = throttle(async function (op) {
  if (['ADD', 'EDIT'].includes(state.showType)) {
    // 基本信息
    let isError;
    await baseRef.value.isValidateFields(op == 0 ? [] : null).catch((error) => {
      isError = true;
      console.warn(error);
    });
    if (isError) return;
    const baseData = baseRef.value.getDataFrom();
    // 销毁档案列表
    fileRef.value.onFinish((data) => {
      const params = {
        op,
        ...baseData,
        fileIds: data.fileList.map((item) => item.id)
      };
      state.showType == 'EDIT' && Object.assign(params, { id: route.query.id });
      destroySave(params).then((result) => {
        if (result.success) {
          message.success('提交成功');
          router.go(-1);
        }
      });
    }, op == 0);
  } else if (state.showType == 'AUDIT') {
    // 销毁鉴定小组
    let isError;
    await teamRef.value.isValidateFields().catch((error) => {
      isError = true;
      console.warn(error);
    });
    const peopleData = teamRef.value.getDataFrom();
    // 审批意见
    // const commentData = commentRef.value.getDataFrom();
    if (isError) return;
    const params = {
      billId: route.query.id,
      ...peopleData
      // ...commentData
    };
    destroyAuidt(params).then((result) => {
      if (result.success) {
        message.success('提交成功');
        router.go(-1);
      }
    });
  } else if (state.showType == 'IDENTIFY') {
    // 审批意见
    // const commentData = commentRef.value.getDataFrom();
    const params = {
      billId: route.query.id
      // ...commentData
    };
    destroyAuthen(params).then((result) => {
      if (result.success) {
        message.success('提交成功');
        router.go(-1);
      }
    });
  } else if (state.showType == 'CONFIRM') {
    // 档案销毁确认
    let isError;
    await confirmRef.value.isValidateFields().catch((error) => {
      isError = true;
      console.warn(error);
    });
    const confirmData = confirmRef.value.getDataFrom();
    if (isError) return;
    const params = {
      id: route.query.id,
      ...confirmData
    };
    destroyConfirm(params).then((result) => {
      if (result.success) {
        message.success('提交成功');
        router.go(-1);
      }
    });
  }
}, 3000);
// 确认销毁
function confirmDestroy() {
  dySignConfig.params = {};
  console.log(phone, 'login-info');
  proxy.$NotificationPubSub.pushParams({
    key: DYNAMICLAYERFORM,
    value: {
      config: dySignConfig,
      form: dySignQuestions,
      name: 'signatureForm'
    }
  });
}
// 预览确认单
function handlePreview() {
  console.log(confirmRef.value.getDataFrom(), 'dataform');
  dyPreviewQuestions.forEach((item) => {
    item.value = confirmRef.value.getDataFrom()[item.key];
  });
  proxy.$NotificationPubSub.pushParams({
    key: DYNAMICLAYERFORM,
    value: {
      config: dyPreviewConfig,
      form: dyPreviewQuestions,
      name: 'previewForm'
    }
  });
}
function handleDown() {
  const captureElement = document.getElementById('confirmBill');
  if (captureElement) {
    const divsToRemove = captureElement.querySelectorAll('.ant-form .ant-row .ant-col.ant-col-6');
    if (divsToRemove.length) {
      // 删除末尾元素
      const divsToHide = divsToRemove[divsToRemove.length - 1] as HTMLElement;
      divsToHide.style.display = 'none'; // 隐藏不需要的内容
      // 直接使用原始的 captureElement 进行截图
      html2canvas(captureElement, { useCORS: true }).then((canvas) => {
        // 恢复被隐藏的内容
        divsToHide.style.display = '';
        canvas.toBlob((blob) => {
          const fileUrl = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = fileUrl;
          link.download = '销毁确认单.jpg';
          link.click();
          window.URL.revokeObjectURL(fileUrl);
        });
      });
    }
  }
}

onBeforeUnmount(() => {
  subscribeSub && subscribeSub.unsubscribe();
  subscribePub && subscribePub.unsubscribe();
  proxy.$NotificationFormSub.clearParams();
  proxy.$NotificationPubSub.clearParams();
});
</script>

<style lang="less" scoped></style>
